package DataStructureAndAlgorithm.CSP.Day04;

//最优灌溉

//最小生成树
//直接套模板
//卡鲁斯卡尔算法

import java.util.Scanner;
import java.util.Arrays;
public class AcWing_3210 {
    static class edge implements Comparable <edge>{
        int a;
        int b;
        int c;
        edge(int a,int b,int c){
            this.a = a;
            this.b = b;
            this.c = c;
        }
        @Override
        public int compareTo(edge temp){
            return this.c - temp.c;
        }
    }
    static int N = 100010;
    static int[] p = new int[N];
    static edge[] e = new edge[N];
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int m = in.nextInt();
        //并查集的初始化代码
        for (int i = 1; i <= n; i++)p[i] = i;
        for (int i = 0; i < m; i++){
            int a = in.nextInt();
            int b = in.nextInt();
            int c = in.nextInt();
            e[i] = new edge(a,b,c);
        }
        Arrays.sort(e,0,m);
        int res = 0;
        for (int i = 0; i < m; i++){
            int a = e[i].a;
            int b = e[i].b;
            int c = e[i].c;
            //如果两个点还没合并
            if (find(a) != find(b)){
                //合并两个点到一个集合
                res += c;
                p[find(a)] = find(b);
            }
        }
        System.out.print(res);
    }
    //并查集的查找和路径压缩
    static int find(int x){
        if (p[x] != x)p[x] = find(p[x]);
        return p[x];
    }
}
